import { ElMessage } from 'element-plus';

/**
 * rgb颜色设置为转换成带透明度的颜色
 * @param {string} sHex  颜色rgb 
 * @param {number} alpha 透明度
 * @returns {string}
 */
export function colorRgba(sHex, alpha = 1) {
  // 十六进制颜色值的正则表达式
  let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  /* 16进制颜色转为RGB格式 */
  let sColor = sHex.toLowerCase()
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = '#'
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    //  处理六位的颜色值
    var sColorChange = []
    for (let i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
    }
    return 'rgba(' + sColorChange.join(',') + ',' + alpha + ')'
  } else {
    return sColor
  }
}

/**
 * 当前时间多久前
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()
  const diff = (now - d) / 1000
  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  } else {
    return ''
  }
}

/**
 * url后面挂载的参数转换的对象
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * 复制数组
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}


/**
 * 深拷贝对象或者素组
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * 数组去重并进行深拷贝
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * 检查一个元素是否有一个类
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * 向元素添加类
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * 删除该对象的类名
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}


let funProto = Function.prototype
let objProto = Object.prototype
let getPrototypeOf = Object.getPrototypeOf
let objToString = objProto.toString
let hasOwnProperty = objProto.hasOwnProperty
let funToString = funProto.toString
// 检查给定的值是否是数组
export const isArray = function (value) {
  return objToString.call(value) === '[object Array]'
}

// 检查给定的值是否是字符串
export const isString = function (value) {
  return objToString.call(value) === '[object String]'
}

// 判断数据类型是否是对象
export const isPlainObject = function (value) {
  //判断数据类型是否是对象类型
  if (!value || objToString.call(value) !== '[object Object]') {
    return false
  }
  let prototype = getPrototypeOf(value)

  if (prototype === null) {
    return true
  }
  let constructor = hasOwnProperty.call(prototype, 'constructor') && prototype.constructor
  return (
    typeof constructor === 'function' && funToString.call(constructor) === funToString.call(Object)
  )
}

// // 深度克隆 array 数组或 json 对象，返回克隆后的副本
export const deepObjClone = function (obj) {
  let weakMap = new WeakMap()
  function clone(obj) {
    if (obj == null) {
      return obj
    }
    if (obj instanceof Date) {
      return new Date(obj)
    }
    if (obj instanceof RegExp) {
      return new RegExp(obj)
    }
    if (typeof obj !== 'object') return obj

    if (weakMap.get(obj)) {
      return weakMap.get(obj)
    }
    let copy = new obj.constructor()
    weakMap.set(obj, copy)
    for (let key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        let value = obj[key]
        copy[key] = clone(value)
      }
    }
    return copy
  }
  return clone(obj)
}

export function getTimeStateStr() {
  let timeNow = new Date();
  let hours = timeNow.getHours();
  if (hours >= 6 && hours <= 10) return `早上好`;
  if (hours >= 10 && hours <= 14) return `中午好`;
  if (hours >= 14 && hours <= 18) return `下午好`;
  if (hours >= 18 && hours <= 24) return `晚上好`;
  if (hours >= 0 && hours <= 6) return `凌晨好`;
}

//下载excel
export function downloadExcel(url) {
  let a = document.createElement("a");
  a.href = url;
  document.body.append(a); // 修复firefox中无法触发click
  a.click();
  URL.revokeObjectURL(a.href);
  a.remove();
}

/**
 * @description 通过路径下载文件
 * @param {Array} url 路径
 * @param {Array} fileName 文件名称加后缀
 * */
export function downloadFile(src, fileName) {
  const xhr = new window.XMLHttpRequest()
  xhr.open('GET', src, true)
  xhr.responseType = 'blob'
  xhr.onload = () => {
    const url = window.URL.createObjectURL(xhr.response)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    link.click()
  }
  xhr.send()
}

//鼠标复制
export function copyContent(content) {//点击复制
  // 创建一个input元素
  let inputDom = document.createElement('textarea');
  // 设置为只读 防止移动端手机上弹出软键盘  
  inputDom.setAttribute('readonly', 'readonly');
  // 给input元素赋值
  inputDom.value = content
  // 将创建的input添加到body
  document.body.appendChild(inputDom);
  // 选中input元素的内容
  inputDom.select();
  // 执行浏览器复制命令
  // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签中的内容）
  // Input要在正常的编辑状态下原生复制方法才会生效
  document.execCommand('copy')
  // const result = document.execCommand('copy')
  // 复制操作后再将构造的标签 移除
  document.body.removeChild(inputDom);
  ElMessage.success('复制成功')
}
